package leetcode.day_2021_03_22_2021_03_28;

import java.util.ArrayList;
import java.util.List;

/**
 * 71. 简化路径
 * https://leetcode-cn.com/problems/simplify-path/
 * https://leetcode-cn.com/problems/simplify-path/solution/javajian-yi-jie-fa-by-wenxuan70-pr1a/
 */
public class LeetCode0071 {

    public static String simplifyPath(String path) {
        if (path==null || path.length()<0) {
            return "/";
        }

        List<String> names = new ArrayList<>();
        for (int i=0; i<path.length(); i++) {
            if(path.charAt(i) != '/') {
                int j = i;
                while (j<path.length() && path.charAt(j)!='/') {
                    j++;
                }
                names.add(path.substring(i, j));
                i = j;
            }
        }

        List<String> res = new ArrayList<>();
        for (int j=0; j<names.size(); j++) {
            if (names.get(j).equals("..")) {
                if (res.size() > 0) {
                    res.remove(res.size()-1);
                }
            } else if (!names.get(j).equals(".")) {
                res.add(names.get(j));
            }
        }
        return "/" + String.join("/", res);
    }

    public static void main(String[] args) {
//        System.out.println(simplifyPath("/home//foo/"));
        System.out.println(simplifyPath("/a/./b/../../c/"));
    }
}
